package cn.tedu.vrd.controller;

import cn.tedu.vrd.entity.User;
import cn.tedu.vrd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class Usercontroller {

    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response, HttpSession session){

        User u =mapper.selectByUsername(user.getUsername());
        if (u!=null){/*用户存在*/
            /*判断用户输入的密码和数据库中的密码是否一致*/
            if (user.getPassword().equals(u.getPassword())){
                if (rem!=null){
//                    创建Cookie 把用户名和密码保存
                    Cookie c1=new Cookie("username",u.getUsername());
                    Cookie c2=new Cookie("password",u.getPassword());
//                    设置Cookie保存时间1个月
                    c1.setMaxAge(60*60*24*30);
                    c2.setMaxAge(60*60*24*30);
//                      下发给客户端浏览器
                    response.addCookie(c1);
                    response.addCookie(c2);
                }

//                保存登录user对象
                session.setAttribute("user",u);
                return 1;/*登录成功*/
            }else {
                return 2;/*密码错误*/
            }
        }
        return 0;/*用户名不存在*/
    }


    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){


        return (User)session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
//        把登录时保存的用户对象删掉
        session.removeAttribute("user");
    }
}
